package com.flowable.service;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class IncrementRetryCountService implements JavaDelegate {

    // 最大重试次数常量
    private static final int MAX_RETRY_COUNT = 3;
    private static final String RETRY_COUNT_VAR = "retryCount";
    private static final String CHECK_RESULT_VAR = "checkResult";
    private static final String AGREE_VALUE = "agree";
    private static final String REFUSE_VALUE = "refuse";

    @Override
    public void execute(DelegateExecution execution) {
        try {
            // 获取当前重试次数
            Integer retryCount = (Integer) execution.getVariable(RETRY_COUNT_VAR);
            if (retryCount == null) {
                retryCount = 0;
            }

            log.info("当前重试次数: {}, 流程ID: {}", retryCount, execution.getProcessInstanceId());

            // 检查是否超过最大重试次数
            if (retryCount >= MAX_RETRY_COUNT) {
                log.warn("已达到最大重试次数({})，流程将终止。流程ID: {}",
                        MAX_RETRY_COUNT, execution.getProcessInstanceId());
                execution.setVariable(CHECK_RESULT_VAR, REFUSE_VALUE);
            } else {
                // 增加重试次数并允许继续流程
                retryCount++;
                execution.setVariable(RETRY_COUNT_VAR, retryCount);
                execution.setVariable(CHECK_RESULT_VAR, AGREE_VALUE);
                log.info("重试次数已增加至: {}, 流程ID: {}", retryCount, execution.getProcessInstanceId());
            }
        } catch (Exception e) {
            log.error("处理重试次数失败，流程ID: {}, 错误: {}",
                    execution.getProcessInstanceId(), e.getMessage(), e);
            throw new RuntimeException("处理重试次数失败", e);
        }
    }
}